package cn.itcast.springboot.security;

import cn.itcast.springboot.content.UserConstant;
import cn.itcast.springboot.entity.UserInfo;
import cn.itcast.springboot.service.UserService;
import cn.itcast.springboot.utils.RedisUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @description:
 * @author: YHL
 * @time: 2021/1/7 11:06 下午
 */
@Component
public class MyUserDetailService implements UserDetailsService {
//    @Reference
//    private UserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//      根据账号 查询数据库 账号 密码 权限信息 封装
        //  根据 账号  查询数据库   账号  密码  权限信息  封装  UserDetails
        //   redis   key    username   密码   权限信息 。。。
        UserInfo userInfo = (UserInfo) RedisUtil.get(UserConstant.SYSUSERINFO + username);
        String password = passwordEncoder.encode(userInfo.getPassword());
        System.out.println("==="+password);
        String authority = userInfo.getAuthority();  //  xx,xx,xx,xx
        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
        return new User(username,password,authorities);
    }
}
